package org.ucas.faker.web.utils.tech;

import java.util.ArrayList;
import java.util.List;

public class Rule{
	
	String center;
	List<String> before;
	List<String> after;
	
	Rule(String rule){
		String [] res = rule.split("\\|");
		//for(String s : res) System.out.print(s+"::");
		//System.out.println(res.length);
		center = res[0];
		
		before = new ArrayList<>();
		after  = new ArrayList<>();
		
		if(res[1].length()!=0){
			for(String s: res[1].split("#")){
				before.add(s);
				//System.out.print(s);
			}			
		}
		if(res.length>=3){
			for(String s: res[2].split("#")){
				after.add(s);
				//System.out.print(s);
			}
		}
		//System.out.println();
	}
	
	int RuleMatch(List<String> sbefore, List<Integer> sbpos,List<String> safter, List<Integer> sapos){
		int distance = 8;
		int after_distance = 2;
		
		int j=before.size()-1,i=sbefore.size()-1;
		
//		for(String s:before) System.out.print(s+" ");
//		System.out.print("#");
//		for(String s:after) System.out.print(s+" ");
//		System.out.println();
		
		//System.out.println("match before");
		for(;j>=0 && i>=0;j--){
			int k = 0;
			for(;i>=0 && k<distance;i--){
				//System.out.println(before.get(j)+"("+j+")"+"\t"+sbefore.get(i)+"("+i+")");
				if(before.get(j).equals(sbefore.get(i))) break;
				if(sbefore.get(i).equals("w")) k -= 3;
				k++;
			}
			if(k>=distance) return -1;
		}
		if(j>=0) return -1;
		int pos_start = i;
		
		j = 0;
		i = 0;
		//System.out.println("match after");
		for(;j<after.size()&& i <safter.size();j++){
			int k = 0;
			for(;i<safter.size() && k< after_distance;i++){
				//System.out.println(after.get(j)+"("+j+")"+"\t"+safter.get(i)+"("+j+")");
				if(after.get(j).equals(safter.get(i))){
					break;
				}
				k++;
			}
			if(k>=after_distance) return -1;
		}
		if(j<after.size()) return -1;
		
		int pos_end = i;
		
		//System.out.print("(---"+pos_start+"   "+pos_end+"---)");
		return sbefore.size()-pos_start+pos_end;
	}
}